package com.gim.connect.netty.init;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;

@Component
public class InitNetty {

    private EventLoopGroup group;
    private Bootstrap bootstrap;
    private Channel channel;

    @PostConstruct
    public void init(){
        // 初始化Netty客户端连接
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        // 添加必要的处理器
                        ch.pipeline().addLast(/* your handlers */);
                    }
                });

        // 连接到服务器
        try {
            channel = bootstrap.connect("localhost", 8080).sync().channel();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("Failed to connect to server", e);
        }
    }

    /**
     * 对外提供发送信息的方法
     * @param message 要发送的消息
     */
    public void sendMessage(Object message) {
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(message);
        } else {
            throw new RuntimeException("Channel is not available");
        }
    }

    @PreDestroy
    public void destroy() {
        // 关闭资源
        if (channel != null) {
            channel.close();
        }
        if (group != null) {
            group.shutdownGracefully();
        }
    }
}
